<template>
	<view class="container">
		<view class="status-bar">
			<swiper class="swiper-container" 
				:indicator-dots="true" 
				indicator-color="rgba(255, 255, 255, 0.5)"
				indicator-active-color="#ffffff"
				:autoplay="true" 
				:interval="3000" 
				:duration="1000"
				circular
			>
				<swiper-item v-for="(item, index) in imgList" :key="index">
					<image :src="item" class="swiper-image" mode="aspectFill" />
				</swiper-item>
			</swiper>
		</view>
		<scroll-view class="category-scroll" scroll-x="true" show-scrollbar="false">
			<view class="category-list">
				<template v-if="categories.length > 0">
					<view 
						class="category-item" 
						v-for="(item, index) in categories" 
						:key="item.dictValue"
						:class="{'active': currentCategory === item.dictValue}"
						@tap="switchCategory(item.dictValue)"
					>
						<text>{{item.dictLabel}}</text>
					</view>
				</template>
				<view v-else class="no-data">暂无分类数据</view>
			</view>
		</scroll-view>
		<scroll-view
			class="main-content"
			scroll-y="true"
			refresher-enabled="true"
			:refresher-triggered="isRefreshing"
			@refresherrefresh="onRefresh"
			@scrolltolower="loadMore"
		>
			<view class="waterfall-wrapper">
				<view class="waterfall-column">
					<view class="waterfall-item" 
						v-for="(item, index) in leftList" 
						:key="index" 
						@click="goToProductDetail(item.id)"
					>
						<image 
							:src="item.image" 
							mode="widthFix" 
							lazy-load
							:data-index="index"
							data-column="left"
							@load="onImageLoad"
						></image>
						<view class="product-info">
							<text class="product-title">{{item.title}}</text>
							<view class="price-section">
								<text class="product-price">¥{{item.price}}</text>
								<text class="sale-count">已售{{item.sold}}件</text>
							</view>
						</view>
					</view>
				</view>
				<view class="waterfall-column">
					<view class="waterfall-item" 
						v-for="(item, index) in rightList" 
						:key="index" 
						@click="goToProductDetail(item.id)"
					>
						<image 
							:src="item.image" 
							mode="widthFix" 
							lazy-load
							:data-index="index"
							data-column="right"
							@load="onImageLoad"
						></image>
						<view class="product-info">
							<text class="product-title">{{item.title}}</text>
							<view class="price-section">
								<text class="product-price">¥{{item.price}}</text>
								<text class="sale-count">已售{{item.sold}}件</text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
import config from '@/config/config.js'

export default {
	data() {
		return {
			imgList: [],
			categories: [],
			currentCategory: '1',
			productList: [],
			leftList: [],
			rightList: [],
			isRefreshing: false,
			loading: false,
			pageNum: 1,
			pageSize: 10,
			hasMore: true,
			imageCache: {},
			loadingImages: new Set(),
		}
	},
	created() {
		this.initSwaperImgs();
		this.distributeItems();
	},
	onLoad() {
		uni.setNavigationBarColor({
			frontColor: '#ffffff',
			backgroundColor: '#000000'
		})
		this.getCategories()
		this.clearExpiredCache()
	},
	onUnload() {
		this.imageCache = {}
		this.loadingImages.clear()
	},
	methods: {
		//查询轮播图信息
		async initSwaperImgs() {
			try {
				// 先从缓存中获取系统配置
				const cachedConfig = uni.getStorageSync('slSysConfig')
				
				if (cachedConfig) {
					console.log('从缓存获取系统配置:', cachedConfig)
					// 如果有缓存数据，直接使用
					this.imgList = cachedConfig.swiperServiceList || []
					return
				}
				
				// 如果没有缓存，调用接口获取
				const result = await this.$http.post(config.api.slconfig.getConfig)
				console.log('系统配置响应:', result)
				
				if (result.data.code === 200) {
					const configData = result.data.data
					
					// 存入缓存
					uni.setStorageSync('slSysConfig', configData)
					
					// 更新轮播图列表
					this.imgList = configData.swiperServiceList || []
				} else {
					throw new Error(result.data.msg || '获取系统配置失败')
				}
			} catch (err) {
				console.error('获取系统配置失败:', err)
				uni.showToast({
					title: err.message || '获取系统配置失败',
					icon: 'none'
				})
			}
		},
		//划分商品页面布局
		distributeItems() {
			this.productList.forEach((item, index) => {
				if (index % 2 === 0) {
					this.leftList.push(item)
				} else {
					this.rightList.push(item)
				}
			})
		},
		onImageLoad(e) {
			// 更新图片实际高度
			const index = e.currentTarget.dataset.index
			const column = e.currentTarget.dataset.column
			const list = column === 'left' ? this.leftList : this.rightList
			if (list[index]) {
				list[index].imageHeight = e.detail.height
			}
		},
		goToProductDetail(productId) {
			uni.navigateTo({
				url: `/subpages/productDetail/productDetail?id=${productId}`
			})
		},
		switchCategory(categoryId) {
			this.currentCategory = categoryId
			// 模拟获取对应分类的商品数据
			this.getProductsByCategory(categoryId)
		},
		async getProductsByCategory(categoryId) {
			try {
				if (!this.loading) {
					uni.showLoading({
						title: '加载中...'
					})
				}
				
				// 重置数据
				this.pageNum = 1
				this.hasMore = true
				this.leftList = []
				this.rightList = []
				
				const result = await this.$http.post(config.api.product.list, {
					categoryId: categoryId,
					pageNum: this.pageNum,
					pageSize: this.pageSize
				}, {
					headers: config.util.getHeaders('form')
				})
				
				if (result.data.code === 200) {
					const products = result.data.rows || []
					
					// 判断是否还有更多数据
					if (products.length < this.pageSize) {
						this.hasMore = false
					}
					
					// 处理数据分配到左右两列
					await this.processProducts(products)
				}
			} catch (err) {
				console.error('获取产品列表失败:', err)
				uni.showToast({
					title: err.message || '获取产品列表失败',
					icon: 'none'
				})
			} finally {
				uni.hideLoading()
			}
		},
		async getCategories() {
			if (this.loading) return
			this.loading = true
			
			try {
				const result = await this.$http.post(config.api.product.category)
				console.log('分类数据响应:', result)
				
				if (result.data.code === 200) {
					this.categories = result.data.data
					console.log('处理后的分类数据:', this.categories)
					
					if (this.categories.length > 0) {
						this.currentCategory = this.categories[0].dictValue
						this.getProductsByCategory(this.currentCategory)
					}
				} else {
					throw new Error(result.data.msg || '获取产品类型失败')
				}
			} catch (err) {
				console.error('获取产品类型失败', err)
				uni.showToast({
					title: err.message || '获取产品类型失败',
					icon: 'none'
				})
			} finally {
				this.loading = false
			}
		},
		async onRefresh() {
			if (this.isRefreshing) return
			
			this.isRefreshing = true
			try {
				// 重置页码
				this.pageNum = 1
				this.hasMore = true
				
				// 重新加载数据
				await Promise.all([
					this.initSwaperImgs(),
					this.getProductsByCategory(this.currentCategory)
				])
			} catch (err) {
				console.error('刷新失败:', err)
			} finally {
				this.isRefreshing = false
				// 停止下拉刷新动画
				uni.stopPullDownRefresh()
			}
		},
		async loadMore() {
			if (this.loading || !this.hasMore) return
			
			this.loading = true
			try {
				this.pageNum++
				const result = await this.$http.post(config.api.product.list, {
					categoryId: this.currentCategory,
					pageNum: this.pageNum,
					pageSize: this.pageSize
				}, {
					headers: config.util.getHeaders('form')
				})
				
				if (result.data.code === 200) {
					const products = result.data.rows || []
					
					// 判断是否还有更多数据
					if (products.length < this.pageSize) {
						this.hasMore = false
					}
					
					// 处理新数据
					await this.processProducts(products)
				}
			} catch (err) {
				console.error('加载更多失败:', err)
				uni.showToast({
					title: '加载更多失败',
					icon: 'none'
				})
			} finally {
				this.loading = false
			}
		},
		async cacheImage(url) {
			if (!url || url.startsWith('data:') || this.loadingImages.has(url)) {
				return url
			}

			try {
				// 检查内存缓存
				if (this.imageCache[url]) {
					return this.imageCache[url]
				}

				// 检查本地存储缓存
				const cachedPath = uni.getStorageSync(`img_cache_${url}`)
				if (cachedPath) {
					this.imageCache[url] = cachedPath
					return cachedPath
				}

				// 标记图片正在加载
				this.loadingImages.add(url)

				// 下载图片
				const downloadRes = await uni.downloadFile({
					url: url
				})

				if (downloadRes.statusCode === 200) {
					// 保存到本地存储和内存缓存
					uni.setStorageSync(`img_cache_${url}`, downloadRes.tempFilePath)
					this.imageCache[url] = downloadRes.tempFilePath
					return downloadRes.tempFilePath
				}

				return url
			} catch (err) {
				console.error('图片缓存失败:', err)
				return url
			} finally {
				this.loadingImages.delete(url)
			}
		},
		async processProducts(products) {
			for (const item of products) {
				const product = {
					id: item.id,
					image: item.productImg || '../../static/images/index_page.png',
					title: item.productName,
					price: item.productPrice,
					sold: item.saleNum || 0
				}

				// 缓存图片
				if (product.image && !product.image.startsWith('../../')) {
					product.image = await this.cacheImage(product.image)
				}

				// 根据列高度分配到左右列
				if (this.getColumnHeight(this.leftList) <= this.getColumnHeight(this.rightList)) {
					this.leftList.push(product)
				} else {
					this.rightList.push(product)
				}
			}
		},
		getColumnHeight(list) {
			return list.reduce((height, item) => height + (item.imageHeight || 200), 0)
		},
		clearExpiredCache() {
			try {
				const now = Date.now()
				const cacheKeys = Object.keys(uni.getStorageInfoSync().keys)
					.filter(key => key.startsWith('img_cache_'))
				
				cacheKeys.forEach(key => {
					const cacheTime = uni.getStorageSync(`${key}_time`)
					if (now - cacheTime > 7 * 24 * 60 * 60 * 1000) { // 7天过期
						uni.removeStorageSync(key)
						uni.removeStorageSync(`${key}_time`)
					}
				})
			} catch (err) {
				console.error('清理缓存失败:', err)
			}
		}
	}
}
</script>

<style>
	.container {
		padding: 0;
		background-color: #f8f8f8;
	}

	.waterfall-wrapper {
		padding: 20rpx;
		display: flex;
		justify-content: space-between;
	}

	.waterfall-column {
		width: 48%;
	}

	.waterfall-item {
		margin-bottom: 20rpx;
		background: #fff;
		border-radius: 12rpx;
		overflow: hidden;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
		transform: translateY(0);
		transition: all 0.3s ease;
	}

	.waterfall-item:active {
		transform: translateY(2rpx);
	}

	.waterfall-item image {
		width: 100%;
		height: auto;
		background-color: #f5f5f5;
	}

	.product-info {
		padding: 16rpx;
	}

	.product-title {
		font-size: 26rpx;
		color: #333;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
		 overflow: hidden;
		line-height: 1.4;
	}

	.price-section {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-top: 12rpx;
	}

	.product-price {
		font-size: 32rpx;
		color: #ff4757;
		font-weight: bold;
	}

	.sale-count {
		font-size: 22rpx;
		color: #999;
	}

	.header {
		position: relative;
		width: 100%;
		height: 300rpx;
		margin-bottom: 20rpx;
	}

	.header-bg {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		z-index: 1;
	}

	.header-content {
		position: relative;
		z-index: 2;
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		background: linear-gradient(to bottom, rgba(0,0,0,0.3), rgba(0,0,0,0.5));
	}

	.header-title {
		color: #ffffff;
		font-size: 36rpx;
		font-weight: bold;
		text-shadow: 0 2rpx 4rpx rgba(0,0,0,0.3);
	}

	.category-scroll {
		background-color: #ffffff;
		padding: 20rpx 0;
		white-space: nowrap;
		position: sticky;
		top: 0;
		z-index: 100;
	}

	.category-list {
		padding: 0 20rpx;
		display: inline-block;
	}

	.category-item {
		display: inline-block;
		padding: 12rpx 30rpx;
		margin-right: 20rpx;
		border-radius: 32rpx;
		background-color: #f5f5f5;
		font-size: 28rpx;
		color: #666;
		transition: all 0.3s;
	}

	.category-item.active {
		background-color: #000;
		color: #fff;
	}

	.status-bar {
		width: 100%;
		height: 350rpx;
		background: #000;
	}

	.swiper-container {
		width: 100%;
		height: 100%;
	}

	.swiper-image {
		width: 100%;
		height: 100%;
		display: block;
	}

	:deep(.wx-swiper-dots) {
		bottom: 20rpx;
	}

	:deep(.wx-swiper-dot) {
		width: 12rpx;
		height: 12rpx;
	}

	.no-data {
		padding: 20rpx;
		text-align: center;
		color: #999;
		font-size: 28rpx;
	}

	.loading {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
	}
</style>
